package com.np.okhttp412demo1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String GET_URL = "https://www.baidu.com/?tn=98010089_dg&ch=2";
    private static final String POST_FORM_URL = "http://192.168.2.23:7002/system-service/api/login";
    private static final String POST_JSON_URL = "http://192.168.2.23:7002/system-service/api/login";
    private TextView mResponse;
    private final OkHttpClient mClient = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mResponse = findViewById(R.id.tv_response);

        findViewById(R.id.btn_sync).setOnClickListener(v -> {
            new Thread(() -> {
                try {
                    Request request = new Request.Builder().url(GET_URL).build();
                    Response response = mClient.newCall(request).execute();
                    String body = response.body().string();

                    runOnUiThread(() -> {
                        mResponse.setText(body);
                    });
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        });

        findViewById(R.id.btn_async).setOnClickListener(v -> {
            new Thread(() -> {
                Request request = new Request.Builder().url(GET_URL).build();
                mClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            throw new IOException("请求失败: " + response.code());
                        }

                        String bodyStr = response.body().string();
                        runOnUiThread(() -> {
                            mResponse.setText(bodyStr);
                        });

                        Headers headers = response.headers();
                        for (int i = 0; i < headers.size(); i++) {
                            Log.i(TAG, String.format("headers.name(%s): %s; headers.value(%s): %s", i, headers.name(i), i, headers.value(i)));
                        }
                    }
                });
            }).start();
        });

        findViewById(R.id.btn_post_form_async).setOnClickListener(v -> {
            new Thread(() -> {
                RequestBody body = new FormBody.Builder().add("account", "admin").add("password", "123456").build();
                Request request = new Request.Builder().url(POST_FORM_URL).post(body).build();

                mClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            throw new IOException("请求失败: " + response.code());
                        }

                        String bodyStr = response.body().string();
                        runOnUiThread(() -> {
                            mResponse.setText(bodyStr);
                        });
                    }
                });
            }).start();
        });

        findViewById(R.id.btn_post_json_async).setOnClickListener(v -> {
            new Thread(() -> {
                RequestBody body = RequestBody.create("{\"username\":\"admin\",\"password\":\"admin@123456\",\"mobile\":\"13543893247\",\"captcha\":\"12310\"}", MediaType.get("application/json"));
                Request request = new Request.Builder().url(POST_JSON_URL).addHeader("Content-Type", "application/json").post(body).build();

                mClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            throw new IOException("请求失败: " + response.code());
                        }

                        String bodyStr = response.body().string();
                        runOnUiThread(() -> {
                            mResponse.setText(bodyStr);
                        });
                    }
                });
            }).start();
        });
    }
}